package lbs;

import android.app.Activity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.util.HashMap;
import java.util.Map;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import utils.ToastUtils;

/**
 * FlutterAMapLocationPlugin
 */
public class FlutterALbsMapPlugin implements MethodCallHandler {
    public static String CHANNEL = "com.ehs2.flutter_albs_map"; // 分析1
    static MethodChannel channe;
    private Activity activity;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mClientOption = null;

    /**
     * Plugin registration.
     */
    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        FlutterALbsMapPlugin plugin = new FlutterALbsMapPlugin(activity12);
        channe.setMethodCallHandler(plugin);
    }

    public FlutterALbsMapPlugin(Activity activity) {
        this.activity = activity;
    }

    @Override
    public void onMethodCall(MethodCall call, Result result) {
        if (call.method.equals("setAK")) {
            result.success(true);
        } else if (call.method.equals("getCurrentLocation")) {

            initClient(new MyLocationListener(result));
        } else {
            result.notImplemented();
        }
    }

    private synchronized void initClient(MyLocationListener listener) {
        AMapLocationClient.updatePrivacyShow(activity,true,true);
        AMapLocationClient.updatePrivacyAgree(activity,true);
        
        if (mLocationClient == null) {
            try {
                mLocationClient = new AMapLocationClient(activity.getApplicationContext());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (mClientOption == null) {
            mClientOption = getDefaultOption();
        }
        // 设置定位参数
        mLocationClient.setLocationOption(mClientOption);
        mLocationClient.setLocationListener(listener);
        mLocationClient.startLocation();
    }

    private synchronized void destroyClient() {
        if (mLocationClient != null) {
            /*
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            try {
                mLocationClient.onDestroy();
                mLocationClient = null;
                mClientOption = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    Map<String, Object> location2map(AMapLocation location) {
        Map<String, Object> json = new HashMap<>();
        if (location != null) {
            int errorCode = location.getErrorCode();
            if (errorCode == 0) {
                json.put("latitude", location.getLatitude());    //获取纬度信息
                json.put("longitude", location.getLongitude());    //获取经度信息

                json.put("country", location.getCountry());    //获取国家
                json.put("province", location.getProvince());    //获取省份
                json.put("city", location.getCity());    //获取城市
                json.put("cityCode", location.getCityCode());
                json.put("district", location.getDistrict());    //获取区县
                json.put("street", location.getStreet());    //获取街道信息

                json.put("locationDescribe", location.getAddress());    //获取位置描述信息
                json.put("adCode", location.getAdCode());    //获取城市adcode


            } else {
                String errorInfo = location.getErrorInfo();// 错误信息
                String locationDetail = location.getLocationDetail();// 错误描述
                ToastUtils.showToast(activity, locationDetail);
            }
        }

        return json;

    }

    private class MyLocationListener implements AMapLocationListener {
        private Result result;

        public MyLocationListener(Result result) {
            this.result = result;
        }

        @Override
        public void onLocationChanged(AMapLocation location) {
            if (location != null) {
                int errorCode = location.getErrorCode();
                if (errorCode == 0) {// 0为 定位成功,其它为定位失败
                    Map<String, Object> map = location2map(location);

                    result.success(map);
                    // 经 度 维度配置
                    destroyClient();
                } else {// 定位失败

                }
            }
        }
    }

    /**
     * 默认的定位参数
     *
     * @return
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);// 可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);// 可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(2000);// 可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);// 可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);// 可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(true);// 可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(true);// 可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);// 可选，
        // 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);// 可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); // 可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); // 可选，设置是否使用缓存定位，默认为true
        return mOption;
    }
}
